import { randString } from '@/util'
import { rsaEncrypt, aesEncrypt } from '@/util/crypt'
import request from '@/util/request'

export function fetchPublicKey() {
  return request({
    url: '/auth/key',
    method: 'get'
  })
}

export function login(username, password, publicKey) {
  const key = randString(16)
  const iv = randString(16)
  const enkey = rsaEncrypt(publicKey, key)
  return request({
    url: '/auth/login',
    method: 'post',
    data: {
      username,
      password: aesEncrypt(password, key, iv),
      enkey,
      iv
    }
  })
}

export function fetchUserInfo() {
  return request({
    url: '/auth/info',
    method: 'get'
  })
}

export function logout() {
  return request({
    url: '/auth/logout',
    method: 'delete'
  })
}
